package com.shouhuobao.take.verify;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.UserBean;
import com.shouhuobao.station.R;
import com.shouhuobao.take.model.StationDetailBean;
import com.shouhuobao.take.model.StationOpenInfoBean;

import droid.frame.ui.utils.Utils;

/**
 * Created by joker on 2017/9/16.
 * 我的驿站信息
 */
public class MyStationInfoActivity extends BaseActivity2 implements View.OnClickListener {

    private ScrollView mScrollView;
    private TextView mStoreNameTV, mStoreKeeperNameTV, mStorePhoneTV, mStoreLocationTV, mStoreDetailLocationTV;

    String levelNameStr = "<font color=#FFFFFF>驿站级别：</font><font color=#1BBD8C>%1$s</font>";
    private MapView mMapView;
    private BaiduMap mBaiduMap;

    private int type;//用来判断是审核中还是审核通过 0 审核通过  1 审核中

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        type = getIntent().getIntExtra("type", 0);
        super.onCreate(savedInstanceState);
        showLoadingDialog(null);
        AppHttp.getInstance().stationDetailData();
        mMapView.onCreate(getContext(), savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_station_info);
        super.findViewById();
        if (type == 0) {
            getAppTitle().setCommonTitle("我的驿站信息");
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) findViewById(R.id.top_LL).getLayoutParams();
            params.topMargin = Utils.dpToPx(16, getResources());
            params.bottomMargin = Utils.dpToPx(16, getResources());
            findViewById(R.id.top_LL).setLayoutParams(params);
        } else {
            getAppTitle().setCommonTitle("审核中");
            findViewById(R.id.title_right_switcher).setVisibility(View.VISIBLE);
            findViewById(R.id.tips_tv).setVisibility(View.VISIBLE);
            TextView rightTV = (TextView) findViewById(R.id.title_right_text);
            Drawable drawable = getResources().getDrawable(R.drawable.seives);
            //这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                    drawable.getMinimumHeight());
            rightTV.setCompoundDrawables(drawable, null, null, null);
            rightTV.setCompoundDrawablePadding(Utils.dpToPx(10, getResources()));
            rightTV.setText("联系客服");
            rightTV.setTextColor(getResources().getColor(R.color.app_font_blue));
            rightTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DialogMgr.showPhoneDialog(getContext(), null);
                }
            });

            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) findViewById(R.id.top_LL).getLayoutParams();
            params.topMargin = Utils.dpToPx(8, getResources());
            params.bottomMargin = Utils.dpToPx(8, getResources());
            findViewById(R.id.top_LL).setLayoutParams(params);
        }
        mScrollView = (ScrollView) findViewById(R.id.scrollView);
        mStoreNameTV = (TextView) findViewById(R.id.store_name_tv);
        mStoreKeeperNameTV = (TextView) findViewById(R.id.storekeeper_name_tv);
        mStorePhoneTV = (TextView) findViewById(R.id.store_phone_tv);
        mStoreLocationTV = (TextView) findViewById(R.id.store_location_tv);
        mStoreDetailLocationTV = (TextView) findViewById(R.id.store_detail_location_tv);
        if (null == AppCache.getUser().getStationId()) {
            findViewById(R.id.compelete_more_info_bt).setVisibility(View.GONE);
        } else {
            Button button = (Button) findViewById(R.id.compelete_more_info_bt);
            button.setVisibility(View.VISIBLE);
            button.setOnClickListener(this);
        }
        initMapView();
        updateTitleView();
    }

    private void updateTitleView() {
        UserBean user = AppCache.getUser();
        TextView levelNameTV = (TextView) findViewById(R.id.station_level_tv);
        ImageView levelImage = (ImageView) findViewById(R.id.level_iv);
        if (user.getLevel() > 10 && user.getLevel() < 20) {//标准
            levelNameTV.setText(Html.fromHtml(String.format(levelNameStr, "标准级驿站")));
            levelImage.setImageResource(R.drawable.myinfo_bz_icon);
        } else if (user.getLevel() > 20) {//专业
            levelNameTV.setText(Html.fromHtml(String.format(levelNameStr, "专业级驿站")));
            levelImage.setImageResource(R.drawable.myinfo_zy_icon);
        } else {
            levelNameTV.setText(Html.fromHtml(String.format(levelNameStr, "入门级驿站")));
            levelImage.setImageResource(R.drawable.myinfo_rm_icon);
        }
    }

    private void setBottomButtonVisibility(StationDetailBean bean) {
        //在完善资料按钮可见的情况下在保存完善信息相关的数据，方便完善信息界面数据展示
        StationOpenInfoBean infoBean = new StationOpenInfoBean();
        infoBean.setStationHousingEstateName(bean.getCommunity());
        infoBean.setStationOpenTime(bean.getServiceTime());
        infoBean.setStationAreaNum(bean.getArea());
        infoBean.setStationWXNum(bean.getWeixin());
        if (isNotEmpty(bean.getStationPics())) {
            String[] picArr = bean.getStationPics().split(",");
            infoBean.setStationInImagePath(picArr[0].replace("[", "").replace("]", "").replace("\"", ""));
            infoBean.setStationOutImagePath(picArr[1].replace("[", "").replace("]", "").replace("\"", ""));
        }
        AppCache.setStationOpenInfoBean(infoBean);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.query_station_info:
                cancelLoadingDialog();
                final ReqResult<StationDetailBean> result = JSON.parser(msg.obj, StationDetailBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result)) {
                            StationDetailBean stationDetail = result.getResult();
                            if (stationDetail != null) {
                                AppCache.getUser().setLevel(stationDetail.getLevel());
                                updateTitleView();
                                mStoreNameTV.setText(stationDetail.getName());
                                mStoreKeeperNameTV.setText(stationDetail.getAdmin());
                                mStorePhoneTV.setText(stationDetail.getPhone());
                                mStoreLocationTV.setText(stationDetail.getCity());
                                mStoreDetailLocationTV.setText(stationDetail.getAddress());
                                addMarkToMap(new LatLng(stationDetail.getLatitude(), stationDetail.getLongitude()));
                                setBottomButtonVisibility(stationDetail);
                            }
                        } else {
                            showToast(result.getMessage());
                        }
                    }
                });
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 初始化地图相关控件
     */
    private void initMapView() {
        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mMapView.showZoomControls(false);//隐藏缩放按钮
        mMapView.showScaleControl(false);//隐藏比例尺
        mMapView.getChildAt(0).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    //允许ScrollView截断点击事件，ScrollView可滑动
                    mScrollView.requestDisallowInterceptTouchEvent(false);
                } else { //不允许ScrollView截断点击事件，点击事件由子View处理
                    mScrollView.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
    }

    private void addMarkToMap(LatLng latLng) {
        BitmapDescriptor bdB = BitmapDescriptorFactory.fromResource(R.drawable.info_map_icon);
        OverlayOptions ooB = new MarkerOptions().position(latLng).icon(bdB).zIndex(9).draggable(true);
        //将marker添加到地图上
        mMapView.getMap().addOverlay(ooB);
        int zoomLevel = 17;// 缩放级别14-1公里, 15-500米
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(latLng, zoomLevel);
        mMapView.getMap().animateMapStatus(u);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //完善用户信息
            case R.id.compelete_more_info_bt:
                Intent intent = new Intent(getContext(), RegVerifyActivity2.class);
                startActivityForResult(intent, 101);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && requestCode == 101) {
            StationDetailBean detailBean = (StationDetailBean) data.getSerializableExtra("result");
            setBottomButtonVisibility(detailBean);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);

    }

    @Override
    protected void onDestroy() {
        if (mBaiduMap != null) {
            mBaiduMap.clear();
        }
        mMapView.onDestroy();
        super.onDestroy();
    }
}
